package org.example.nio_demo;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @ClassName DemoChannel2
 * @Description
 * @Author zhangsw
 * @Date 2020/11/9 23:02
 * @Version 1.0
 */
public class DemoChannel2 {
    public static void main(String[] args) throws IOException {
        long startTime = System.currentTimeMillis();//3068-2515-2702
        //使用直接缓冲区完成文件的复制(内存映射文件)
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\Learn\\a.zip"), StandardOpenOption.READ);
        /**
         * 参数为 StandardOpenOption.CREATE 如果存在就覆盖
         * 参数为 StandardOpenOption.CREATE_NEW 如果存在就报错，不存在就创建
         */
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\Users\\zhangsw\\Desktop\\Learn\\b.zip"),
                StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //内存映射文件 和 allocateDirect效果一样，只是获取形式不同
        MappedByteBuffer inMappedBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMappedBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

        //直接对缓冲区进行数据读写
        byte[] dst = new byte[inMappedBuffer.limit()];
        inMappedBuffer.get(dst);
        outMappedBuffer.put(dst);

        inChannel.close();
        outChannel.close();

        long endTime = System.currentTimeMillis();
        System.err.println(endTime - startTime);
    }
}
